package org.jflame.fx.control;

import org.jflame.fx.assets.JFLResources;
import org.jflame.fx.util.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;

/**
 * 自定义文件选择控件
 * 
 * @author yucan.zhang
 */
public class FileField extends StackPane {

    private TextField fileText;
    private Button fileButton;

    private FileChooser fileChooser = new FileChooser();
    private SelectionMode selectionMode = SelectionMode.SINGLE;// 是否可多选择文件
    private ObjectProperty<List<File>> selectedFileProperty;

    public FileField() {
        getStylesheets().add(JFLResources.load("css/fileField.css")
                .toExternalForm());
        getStyleClass().add("file-field");
        setAlignment(Pos.CENTER_RIGHT);

        fileText = new TextField();
        fileText.setEditable(false);

        fileButton = new Button(JFLResources.getString("pub.choose"));
        fileButton.setMnemonicParsing(false);
        fileButton.setOnAction((event) -> {
            handleFileChoose(event);
        });

        getChildren().addAll(fileText, fileButton);
    }

    protected void handleFileChoose(ActionEvent event) {
        List<File> selectedFiles = null;
        if (selectionMode == SelectionMode.MULTIPLE) {
            selectedFiles = fileChooser.showOpenMultipleDialog(super.getScene().getWindow());
        } else {
            File selectedFile = fileChooser.showOpenDialog(super.getScene().getWindow());
            if (selectedFile != null) {
                selectedFiles = List.of(selectedFile);
            }
        }
        List<String> selectedFilePath = null;
        List<String> oldselectedFilePath = getSelectedFilePaths();
        if (Utils.isNotEmpty(selectedFiles)) {
            selectedFilePath = extractFilePaths(selectedFiles);
        }
        if (!Utils.elementEquals(oldselectedFilePath, selectedFilePath)) {
            selectedFileProperty().set(selectedFiles);
        }
        fileText.setText(String.join(",", selectedFilePath));
    }

    public final ObjectProperty<List<File>> selectedFileProperty() {
        if (selectedFileProperty == null) {
            selectedFileProperty = new ReadOnlyObjectWrapper<>(this, "selectedFile");
        }
        return selectedFileProperty;
    }

    /**
     * 返回首个选择文件的路径
     * 
     * @return
     */
    public String getFirstSelectedFilePath() {
        File f = getFirstSelectedFile();
        return f == null ? null : f.getPath();
    }

    /**
     * 返回首个选择的文件对象
     * 
     * @return File
     */
    public File getFirstSelectedFile() {
        List<File> selectedFiles = selectedFileProperty().getValue();
        return Utils.isEmpty(selectedFiles) ? null : selectedFiles.get(0);
    }

    /**
     * 返回所有选择的文件
     * 
     * @return
     */
    public List<File> getSelectedFiles() {
        return selectedFileProperty().getValue();
    }

    private List<String> getSelectedFilePaths() {
        return extractFilePaths(selectedFileProperty().getValue());
    }

    private List<String> extractFilePaths(List<File> selectedFiles) {
        List<String> paths = new ArrayList<>();
        if (Utils.isNotEmpty(selectedFiles)) {
            selectedFiles.forEach(f -> {
                paths.add(f.getPath());
            });
        }
        return paths;
    }

    public SelectionMode getSelectionMode() {
        return selectionMode;
    }

    public void setSelectionMode(SelectionMode selectionMode) {
        this.selectionMode = selectionMode;
    }

    public final String getText() {
        return fileButton.getText();
    }

    /**
     * 设置选择按钮的文本,默认是"选择文件"
     * 
     * @param text
     */
    public final void setText(String text) {
        fileButton.setText(text);
    }

    /**
     * 增加要过滤掉的文件类型. 示例:addExtensionFilter("图片","*.jpg","*.png")
     * 
     * @param desc 显示在文件类型选择框里的名称
     * @param extensions 要过滤掉的文件类型,格式:*.ext
     */
    public void addExtensionFilter(String desc, String... extensions) {
        fileChooser.getExtensionFilters()
                .add(new ExtensionFilter(desc, extensions));
    }

}
